// action: "POP"
// block: ƒ block(prompt)
// createHref: ƒ createHref(location)
// go: ƒ go(n)
// goBack: ƒ goBack()
// goForward: ƒ goForward()
// length: 12
// listen: ƒ listen(listener)
// location: {pathname: "/detail/11", search: "", hash: "", state: undefined}
// push: ƒ push(path, state)
// replace: ƒ replace(path, state)
export default function createBrowserHistory() {
    const history = window.history
    let action = 'POP';
    let location = {
        pathname: '',
        search: '',
        hash: '',
        state: history.state
    }
    const listeners = [];

    // 浏览器前后点击时触发
    window.addEventListener('popstate', (e) => {
        const {pathname, hash, search} = e.currentTarget.location
        update({pathname, hash, search, state: ''})
    })

    function update(location) {
        listeners.forEach(fn => fn(location))
    }

    function block() {

    }
    function createHref(location) {

    }
    function go(n) {
        action = 'POP'
        history.go(n);
    }

    function goBack() {
        go(-1);
    }

    function goForward() {
        go(1);
    }

    function listen(listener) {
        listeners.push(listener);
    }

    function push(path, state) {
        // 更改action
        action = 'PUSH';
        history.pushState(state, state, path);
        // 更新
        update({
            pathname: path,
            search: '',
            hash: '',
            state
        })
    }

    function replace(path, state) {
        action = 'REPLACE'
        history.replaceState(state, state, path);
        update({
            pathname: path,
            search: '',
            hash: '',
            state
        })
    }



    return {
        action,
        length: history.length,
        block,
        go,
        goBack,
        goForward,
        listen,
        push,
        replace,
        createHref,
        location
    }
}